-- 玩家数据库
-- Author: Colocaisa
-- Date: 2019-05-17
local log = require "log";


---@class db_player @玩家数据库类
---@field private redis_prefix string @数据缓存前缀
---@field private valid_time number @数据缓存有效期
local db_player = {}
local redis_prefix = 'player:';
local valid_time = 3600;

---根据玩家GUID查找玩家
---@type fun(guid: string): table
---@param guid string
---@return table
function db_player:find_player_by_guid(guid)
    local key = redis_prefix..'guid_'..guid;
    local result = self:hgetall(key);
    if not result then
        result = self:player_select_by_guid(guid);
    end

    self:expire_player(result);
    result = result and result[1];
    -- log.dump(result, "find_player_by_guid");
    return result;
end

---根据玩家名字查找玩家
---@param name string
---@return table
function db_player:find_player_by_name(name)
    print("find_player_by_name", name);
    local key = redis_prefix..name;
    local result = self:hgetall(key);
    if not result then
        result = self:player_select_by_name(name);
    end

    self:expire_player(result);
    result = result and result[1];
    log.dump(result, "find_player_by_name");
    return result;
end

---根据账户GUID查找玩家
---@param acc_guid string
---@return table
function db_player:find_player_by_account(acc_guid)

end

-- 设置缓存有效期
function db_player:expire_player(result)
    if not result then return end
    for _, plr in pairs(result) do
        local plr_guid = plr.guid
        local plr_name = plr.name
        self:expire(redis_prefix.."name_"..plr_name, valid_time);
        self:expire(redis_prefix.."guid_"..plr_guid, valid_time);
    end
end

return db_player;
